package com.chb.javabasic.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Slf4j
public class MybatisUserDemo {
    public static void main(String[] args) throws IOException {
        // 加载配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 2. 创建 SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 3. 获取 SqlSession
        try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
            // 获取 Mapper 接口的代理对象
            MybatisUserMapper mybatisUserMapper = sqlSession.getMapper(MybatisUserMapper.class);

//            log.info("根据id查询用户,查询id为1的用户信息：");
//            // 根据id查询用户
//            MybatisUser user = mybatisUserMapper.getUserById(1L);
//            System.out.println(user);
//
//            log.info("查询所有用户的用户信息：");
//            // 查询所有用户
//            List<MybatisUser> users = mybatisUserMapper.geAlltMybatisUsers();
//            for (MybatisUser user1 : users) {
//                System.out.println(user1);
//            }

//            log.info("插入用户信息：");
//            MybatisUser mybatisUser = new MybatisUser();
//            mybatisUser.setUsername("amy");
//            mybatisUser.setPassword("123456");
//            mybatisUser.setEmail("amy@email");
//            mybatisUser.setCreatedAt(Timestamp.valueOf(LocalDateTime.now()));
//            mybatisUser.setUpdatedAt(Timestamp.valueOf(LocalDateTime.now()));
//            mybatisUserMapper.insertUser(mybatisUser);
//
//            log.info("查询所有用户的用户信息：");
//            // 查询所有用户
//            List<MybatisUser> users = mybatisUserMapper.geAlltMybatisUsers();s
//            for (MybatisUser user1 : users) {
//                System.out.println(user1);
//            }

//            log.info("更新用户信息前：");
//            MybatisUser user = mybatisUserMapper.getUserById(18L);
//            System.out.println(user);
//            log.info("更新用户信息后：");
//            user.setUsername("luxi");
//            mybatisUserMapper.updateUser(user);
//            System.out.println(user);
//            log.info("删除用户");
//            mybatisUserMapper.deleteUser(18L);

            log.info("使用通用Mapper查询所有用户：");
            MybatisUserMapper userMapper = sqlSession.getMapper(MybatisUserMapper.class);
            List<MybatisUser> list = userMapper.geAlltMybatisUsers();
            for (MybatisUser mybatisUser : list) {
                System.out.println(mybatisUser);
            }
        }

    }
}
